package com.rem.web;

import com.rem.pojo.Book;
import com.rem.pojo.Cart;
import com.rem.pojo.CartItem;
import com.rem.service.BookService;
import com.rem.service.impl.BookServiceImpl;
import com.rem.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author remembrance
 * @version 1.0
 * @date 2021/10/13 14:58
 */
public class CartServlet extends BaseServlet{
//    private Cart cart = new Cart();
    private BookService bookService = new BookServiceImpl();

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/pages/cart/cart.jsp").forward(req,resp);
    }

    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        Integer id = WebUtils.parseInt(req.getParameter("id"), 1);
        Book book = bookService.queryBookById(id);
        CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());

        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart == null) {
            cart = new Cart();
            req.getSession().setAttribute("cart",cart);
        }
        cart.addCartItem(cartItem);
//        System.out.println(cart);
        String lastName = cartItem.getName();
        req.getSession().setAttribute("lastName",lastName);

        req.getSession().setAttribute("cart",cart);


        resp.sendRedirect(req.getHeader("Referer"));
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = WebUtils.parseInt(req.getParameter("id"), 0);
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        cart.deleteCartItem(id);
        if (cart.getItems().size() == 0){
            req.getSession().invalidate();
        }
        resp.sendRedirect("cartServlet?action=page");
    }

    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect("cartServlet?action=page");
    }

    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        Integer id = WebUtils.parseInt(req.getParameter("id"), 1);
        Integer count = WebUtils.parseInt(req.getParameter("count"), 1);
        // 获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart != null) {
            // 修改商品数量
            cart.updateCount(id,count);
            // 重定向回原来购物车展示页面
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }
}
